shader_type canvas_item;
// USING https://www.shadertoy.com/view/XtBXDw for 3dclouds and https://www.shadertoy.com/view/4dsXWn for 2d clouds
uniform float iTime;
uniform float sun_radius;
uniform float noise_freq;
uniform sampler2D Noise;
uniform vec3 SUN_POS; //normalize this vector in script!
uniform vec4 sun_color: hint_color;
uniform sampler2D space_env_texture;

lowp vec3 rotate_y(vec3 v, float angle)
{
	lowp float ca = cos(angle); lowp float sa = sin(angle);
	return v*mat3(
		vec3(+ca, +.0, -sa),
		vec3(+.0,+1.0, +.0),
		vec3(+sa, +.0, +ca));
}

lowp vec3 rotate_x(vec3 v, float angle)
{
	lowp float ca = cos(angle); lowp float sa = sin(angle);
	return v*mat3(
		vec3(+1.0, +.0, +.0),
		vec3(+.0, +ca, -sa),
		vec3(+.0, +sa, +ca));
}
lowp float rand(vec2 co) {return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);}//just random function. Used for stars.

lowp float noise( in vec3 pos )
{
    pos*=0.01;
	lowp float  z = pos.z*256.0;
	lowp vec2 offz = vec2(0.317,0.123);
	lowp vec2 uv = pos.xy + offz*floor(z); 
	return mix(textureLod( Noise, uv ,0.0).x,textureLod( Noise, uv+offz ,0.0).x,fract(z));
}

lowp float get_noise(vec3 p, float FBM_FREQ)
{
	lowp float
	t  = 0.51749673 * noise(p); p *= FBM_FREQ;
	t += 0.25584929 * noise(p); p *= FBM_FREQ;
	t += 0.12527603 * noise(p); p *= FBM_FREQ;
	t += 0.06255931 * noise(p);
	return t;
}

void fragment(){
	lowp vec2 uv = UV; 
    uv.x = 2.0 * uv.x - 1.0;
    uv.y = 2.0 * uv.y - 1.0;
	lowp vec3 rd = normalize(rotate_y(rotate_x(vec3(0.0, 0.0, 1.0),-uv.y*3.1415926535/2.0),-uv.x*3.1415926535)); //transform UV to spherical panorama 3d coords
	lowp vec4 space=vec4(0.0);
	lowp float sun_amount = min(pow(max(dot(rd, SUN_POS), 0.0), 500.0/sun_radius) * 100.0, 1.0);
	lowp float alpha = sun_amount;
	sun_amount *= clamp(get_noise(rd-SUN_POS*iTime, noise_freq)+0.3,0.5,1.0);
	space = sun_color*sun_amount;
	space.rgb =mix(texture(space_env_texture, SCREEN_UV).rgb, space.rgb,alpha);
	COLOR=vec4(space.rgb,1.0);
}